import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class Solution54 {
    public List<Integer> spiralOrder(int[][] matrix){
        List<Integer> res = new LinkedList<>();
        int m = matrix.length,n = matrix[0].length;
        int upper_Bound = 0,down_Bound = m - 1;
        int left_Bound = 0,right_Bound = n - 1;

        while(res.size() < m*n){
            if(upper_Bound <= down_Bound){
                for (int i = left_Bound; i <= right_Bound; i++) {
                    res.add(matrix[upper_Bound][i]);
                }
                upper_Bound++;
            }
            if(left_Bound <= right_Bound){
                for (int i = upper_Bound; i <= down_Bound; i++) {
                    res.add(matrix[i][right_Bound]);
                }
                right_Bound--;
            }
            if(upper_Bound <= down_Bound){
                for (int j = right_Bound; j >= left_Bound ; j--) {
                    res.add(matrix[down_Bound][j]);
                }
                down_Bound--;
            }
            if (left_Bound <= right_Bound){
                for (int i = down_Bound; i >= upper_Bound; i--) {
                    res.add(matrix[i][left_Bound]);
                }
                left_Bound++;
            }
        }
        return res;
    }
}
